#!/bin/bash
# Unified Build Script for Ollama Translator - All Platforms

echo "🚀 Ollama Translator - Cross-Platform Build System"
echo "================================================"

# Detect current platform
case "$(uname -s)" in
    Darwin)
        PLATFORM="macos"
        echo "📱 Detected platform: macOS"
        ;;
    Linux)
        PLATFORM="linux" 
        echo "🐧 Detected platform: Linux"
        ;;
    CYGWIN*|MINGW32*|MSYS*|MINGW*)
        PLATFORM="windows"
        echo "🪟 Detected platform: Windows"
        ;;
    *)
        echo "❌ Unsupported platform: $(uname -s)"
        exit 1
        ;;
esac

# Function to check Python
check_python() {
    if command -v python3 &> /dev/null; then
        PYTHON_CMD="python3"
    elif command -v python &> /dev/null; then
        PYTHON_CMD="python"
    else
        echo "❌ Python not found. Please install Python 3.8+"
        exit 1
    fi
    
    echo "✅ Python found: $($PYTHON_CMD --version)"
}

# Function to install dependencies
install_deps() {
    echo "📦 Installing dependencies..."
    
    # Check if uv is available
    if command -v uv &> /dev/null; then
        echo "Using uv for dependency management..."
        uv sync
    else
        echo "Using pip for dependency management..."
        $PYTHON_CMD -m pip install --upgrade pip
        $PYTHON_CMD -m pip install requests PyQt6 PyInstaller
    fi
}

# Function to build for current platform
build_current() {
    echo "🔨 Building for $PLATFORM..."
    
    case "$PLATFORM" in
        "macos")
            ./build_macos.sh
            ;;
        "linux")
            ./build_linux.sh
            ;;
        "windows")
            # On Windows, we need to run the batch file
            if [[ "$PLATFORM" == "windows" ]]; then
                cmd //c "build_windows.bat"
            else
                echo "❌ Windows build script must be run on Windows"
                exit 1
            fi
            ;;
    esac
}

# Function to build for all platforms (if possible)
build_all_platforms() {
    echo "🌍 Attempting to build for all platforms..."
    
    # Build for current platform first
    build_current
    
    # Try to build for other platforms using the Python script
    if command -v "$PYTHON_CMD" &> /dev/null; then
        echo ""
        echo "🔄 Building for other platforms using Python script..."
        $PYTHON_CMD build_cross_platform.py
    fi
}

# Function to show build results
show_results() {
    echo ""
    echo "📊 Build Results"
    echo "================"
    
    # Check what was built
    BUILT_PLATFORMS=()
    
    if [ -f "dist/ollama_translate" ] || [ -f "dist/ollama_translate.exe" ]; then
        BUILT_PLATFORMS+=("current")
    fi
    
    if [ -f "dist_macos/ollama_translate" ]; then
        BUILT_PLATFORMS+=("macos")
    fi
    
    if [ -f "dist_windows/ollama_translate.exe" ]; then
        BUILT_PLATFORMS+=("windows")
    fi
    
    if [ -f "dist_linux/ollama_translate" ]; then
        BUILT_PLATFORMS+=("linux")
    fi
    
    if [ ${#BUILT_PLATFORMS[@]} -eq 0 ]; then
        echo "❌ No builds were successful"
        exit 1
    fi
    
    echo "✅ Successful builds: ${BUILT_PLATFORMS[*]}"
    
    # Show file sizes
    echo ""
    echo "📁 Built executables:"
    for platform in "dist" "dist_macos" "dist_windows" "dist_linux"; do
        if [ -d "$platform" ]; then
            exe=""
            if [ -f "$platform/ollama_translate" ]; then
                exe="$platform/ollama_translate"
            elif [ -f "$platform/ollama_translate.exe" ]; then
                exe="$platform/ollama_translate.exe"
            fi
            
            if [ -n "$exe" ]; then
                size=$(du -h "$exe" 2>/dev/null | cut -f1 || echo "N/A")
                echo "  $exe ($size)"
            fi
        fi
    done
}

# Function to create distribution package
create_package() {
    echo ""
    echo "📦 Creating distribution package..."
    
    # Create releases directory
    mkdir -p releases
    
    # Get version from pyproject.toml
    VERSION="0.1.0"
    if [ -f "pyproject.toml" ]; then
        VERSION=$(grep "^version" pyproject.toml | head -1 | cut -d'"' -f2)
    fi
    
    # Create timestamp
    TIMESTAMP=$(date +%Y%m%d_%H%M%S)
    
    # Create package name
    PACKAGE_NAME="ollama_translate_${VERSION}_${PLATFORM}_${TIMESTAMP}"
    
    # Copy relevant build artifacts
    mkdir -p "releases/$PACKAGE_NAME"
    
    # Copy built executables
    if [ -d "dist" ]; then
        cp -r dist/* "releases/$PACKAGE_NAME/" 2>/dev/null || true
    fi
    
    if [ -d "dist_$PLATFORM" ]; then
        cp -r "dist_$PLATFORM"/* "releases/$PACKAGE_NAME/" 2>/dev/null || true
    fi
    
    # Copy README and documentation
    cp README.md BUILD.md "releases/$PACKAGE_NAME/" 2>/dev/null || true
    
    echo "✅ Package created: releases/$PACKAGE_NAME"
}

# Main execution
main() {
    echo ""
    
    # Check Python
    check_python
    
    # Install dependencies
    install_deps
    
    # Make build scripts executable
    chmod +x build_macos.sh build_linux.sh build_cross_platform.py 2>/dev/null || true
    
    # Ask user what to build
    echo ""
    echo "🔧 Build Options:"
    echo "  1) Build for current platform only ($PLATFORM)"
    echo "  2) Build for all platforms (if possible)"
    echo ""
    
    read -p "Select option (1-2, default 1): " choice
    
    case "${choice:-1}" in
        1)
            build_current
            ;;
        2)
            build_all_platforms
            ;;
        *)
            echo "❌ Invalid choice"
            exit 1
            ;;
    esac
    
    # Show results
    show_results
    
    # Create package
    create_package
    
    # Final instructions
    echo ""
    echo "🎉 Build completed successfully!"
    echo ""
    echo "📋 Next steps:"
    echo "  1. Ensure Ollama service is running: ollama serve"
    echo "  2. Test the built executable"
    echo "  3. Check the BUILD.md file for installation instructions"
    echo ""
    echo "📁 Built files are in:"
    echo "  - dist/ (current platform)"
    echo "  - dist_macos/ (macOS build)"  
    echo "  - dist_windows/ (Windows build)"
    echo "  - dist_linux/ (Linux build)"
    echo "  - releases/ (distribution packages)"
    echo ""
}

# Run main function
main